package org.zachary.agent.infrastructure.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.Setter;
import org.springframework.core.io.ClassPathResource;
import org.zachary.agent.domain.aggregate_model.user_credit.UserCredit;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class CreditScoreCalculator {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 用户信用实体类
    @Setter
    @Getter
    public static class UserCreditTemp {
        // Getters and setters
        private Integer userId;
        private String name;
        private String idCard;
        private String workType;
        private String education;
        private String maritalStatus;
        private Double annualIncome;

        @Override
        public String toString() {
            return "UserCreditTemp{" +
                    "userId=" + userId +
                    ", name='" + name + '\'' +
                    ", idCard='" + idCard + '\'' +
                    ", workType='" + workType + '\'' +
                    ", education='" + education + '\'' +
                    ", maritalStatus='" + maritalStatus + '\'' +
                    ", annualIncome=" + annualIncome +
                    '}';
        }
    }

    public static Map<String, Object> calculateCreditScore(String username,UserCredit u) {
        // 创建测试用户
        UserCreditTemp user = new UserCreditTemp();
        user.setUserId(u.getId());
        user.setName(username);
        user.setIdCard(u.getIdNumber());
        user.setWorkType(u.getJobType());
        user.setEducation(u.getQualification());
        user.setMaritalStatus(u.getMaritalStatus());
        user.setAnnualIncome(u.getAnnualIncome());
        System.out.println(user);

        try {
            // 获取Python脚本路径
            ClassPathResource resource = new ClassPathResource("python/test.py");
            File scriptFile = resource.getFile();
            String scriptPath = scriptFile.getAbsolutePath();

            // 创建Python进程
            ProcessBuilder pb = new ProcessBuilder("python", scriptPath);
            pb.redirectErrorStream(true);
            Process process = pb.start();

            // 将用户数据转换为JSON并写入Python进程
            try (OutputStream outputStream = process.getOutputStream();
                 PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream))) {

                String userJson = objectMapper.writeValueAsString(user);
                writer.write(userJson);
                writer.flush();
            }

            // 读取Python输出
            try (InputStream inputStream = process.getInputStream();
                 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {

                StringBuilder output = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line);
                }

                // 等待进程结束
                int exitCode = process.waitFor();
                if (exitCode != 0) {
                    throw new RuntimeException("Python script exited with error code: " + exitCode);
                }

                // 解析JSON响应
                return objectMapper.readValue(output.toString(), HashMap.class);
            }
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException("Error calculating credit score", e);
        }
    }


}